<template>
  <div class="header">
    <div class="left">
      <img class="left_logo" src="../assets/images/header_logo.png" alt="" />
      <!-- <img class="left_logo2" src="../assets/images/header_logo2.png" alt=""> -->
      <!-- <span class="logo_text">O</span> -->
      <span class="title title2">Omnicity</span>
      <span class="title">运维管理后台</span>
      <div class="dropdown">
        <el-dropdown
          class="dropdown_pro"
          popper-class="dropdown_pro_popper"
          trigger="hover"
          @command="handleCommand"
          @visible-change="dropdownVisibleChange"
        >
          <div class="el-dropdown-link">
            <span class="dropdown_text">
              {{ currentProjectInfo.projectName }}</span
            >
            <img
              class="img_icon"
              :class="showDropdown ? 'showDropdown' : ''"
              src="../assets/images/pull_down_icon.png"
            />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <!-- <el-dropdown-item command="1">O平台</el-dropdown-item>
              <el-dropdown-item command="2">S平台</el-dropdown-item> -->
              <template v-for="(item, index) in userProjectRsps">
                <el-dropdown-item
                  :class="{
                    commonHeader_selected:
                      currentProjectInfo.projectId == item.projectId,
                  }"
                  :command="index"
                  @click="changeProject(item)"
                >
                  <img
                    class="pro_icon"
                    src="../assets/images/images_new/pro_icon.png"
                    alt=""
                    v-if="currentProjectInfo.projectId != item.projectId"
                  />
                  <img
                    class="pro_icon"
                    src="../assets/images/images_new/pro_selected_icon.png"
                    alt=""
                    v-else
                  />
                  <span>{{ item.projectName }}</span>
                  <img
                    class="pro_selected"
                    src="../assets/images/images_new/pro_selected.png"
                    alt=""
                    v-if="currentProjectInfo.projectId == item.projectId"
                  />
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="right">
      <div class="msg_box" @click="pushMessage">
        <img
          class="message"
          src="../assets/images/images_new/news_icon.png"
          alt=""
        />
        <span
          class="messageNum"
          :class="{ messageNum2: msgNum >= 100 }"
          v-if="msgNum && msgNum > 0"
        >
          <span class="msg_num" v-if="msgNum < 100">{{ msgNum }}</span>
          <span class="msg_num" v-else>99+</span>
        </span>
      </div>
      <div class="user">
        <el-dropdown
          trigger="hover"
          popper-class="dropdown_user_popper"
          @command="handleCommand2"
          @visible-change="dropdownVisibleChange2"
        >
          <span class="el-dropdown-link">
            <span class="userName">
              <span class="titleRight">
                <span>{{ filterRealName(userInfo.realName) }}</span>
              </span>
            </span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="0" class="dropdown_userInfo">
                <div class="realName">
                  <span>{{ userInfo.realName }}</span>
                </div>
                <div class="info_type">
                  <span v-if="userInfo.type == 0">超级管理员</span>
                  <span v-if="userInfo.type == 1">平台管理员</span>
                  <span v-if="userInfo.type == 2">平台用户</span>
                  <span v-if="userInfo.type == 3">项目管理员</span>
                  <span v-if="userInfo.type == 4">普通用户</span>
                </div>
              </el-dropdown-item>
              <el-dropdown-item
                command="2"
                class="dropdown_change dropdown_changeUserInfo"
              >
                <div class="change_item info">
                  <img
                    class="head_icon"
                    src="../assets/images/images_new/header_userInfo.png"
                    alt=""
                  />
                  <span>个人信息</span>
                </div>
              </el-dropdown-item>
              <el-dropdown-item
                command="1"
                class="dropdown_change dropdown_changePw"
              >
                <div class="change_item pw">
                  <img
                    class="head_icon"
                    src="../assets/images/images_new/header_pw.png"
                    alt=""
                  />
                  <span>修改密码</span>
                </div>
              </el-dropdown-item>
              <el-dropdown-item
                command="3"
                class="dropdown_change dropdown_logout"
              >
                <div class="change_item logout">
                  <img
                    class="head_icon"
                    src="../assets/images/images_new/header_logout.png"
                    alt=""
                  />
                  <span>退出登录</span>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
  <changePassword
    :dialogVisible="dialogVisible"
    @closeDialog="closeDialog"
  ></changePassword>
  <Information
    :dialogVisible="dialogVisible2"
    :propInfo="userInfo"
    @closeDialog="closeDialog2"
  ></Information>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { authLogout, queryMenuTree } from "../http/user";
import { useMain, store } from "../store/index";
import changePassword from "./changePassword.vue";
import Information from "./Information.vue";
import { storeToRefs } from "pinia";
import { userMsgCount } from "@/http/message";
import { getOptions, setTopics, setTopics2 } from "@/utils/mqttConfig.js";
import main from "../main";
import * as mqtt from "mqtt/dist/mqtt.min";
import {
  deleteCookie,
  filterMenuData,
  getenv,
  getMqttUrl,
} from "@/utils/utils";
import { qzsList } from "@/utils/menuList";

const router = useRouter();
const useMainStore = useMain(store); //pinia

//currentProjectInfo 当前项目信息 userProjectRsps 所有项目列表 userInfo 用户信息
//storeToRefs 保持响应式
let { currentProjectInfo, userProjectRsps, userInfo, msgNum } =
  storeToRefs(useMainStore);

//点击退出登录按钮
const logout = () => {
  // @ts-ignore 取消单行ts验证
  ElMessageBox.confirm("确定退出登录吗?", "退出确认", {
    confirmButtonText: "是",
    cancelButtonText: "否",
    type: "none",
    // showClose: false
  })
    .then(() => {
      authLogout().then((res) => {
        useMainStore.mqtt_close(); //断开MQTT
        useMainStore.updatedShowDrawer(false); //关闭实时消息弹窗
        useMainStore.updatedMsgList([]); //清空消息列表
        useMainStore.updatedAuthToken("");
        useMainStore.updatedRefreshToken("");
        useMainStore.updatedUserInfo({});
        useMainStore.updatedUserProjectRsps([]);
        useMainStore.updatedMenuListInfo([]);
        useMainStore.updatedProjectInfo({});
        deleteCookie("authToken");
        deleteCookie("refreshToken");
        router.push("/login");
      });
    })
    .catch(() => {});
};
interface Iuser {
  id?: string;
  loginName?: string;
  mobile?: string;
  realName?: string;
  state?: number;
  type?: number;
}

//是否打开修改密码弹窗
const dialogVisible = ref(false);

//是否打开个人信息弹窗
const dialogVisible2 = ref(false);

//选择下拉菜单
const handleCommand = (command: string | number | object) => {
  // console.log('command', command);
};

let projectId = ref(""); //项目id
//切换项目
const changeProject = (item: any) => {
  if (currentProjectInfo.value.projectId != item.projectId) {
    //@ts-ignore 取消单行ts验证
    ElMessageBox.confirm(
      "确定切换到" + item.projectName + "吗?",
      "项目切换确认",
      {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "none",
        // showClose: false
      }
    )
      .then(() => {
        useMainStore.mqtt_close(); //断开MQTT
        useMainStore.updatedShowDrawer(false); //关闭实时消息弹窗
        useMainStore.updatedMsgList([]); //清空消息列表
        useMainStore.updatedProjectInfo(item);
        projectId.value = item.projectId;
        getMenuTree(); //获取用户资源
        getMsgNum(); //获取消息数
      })
      .catch(() => {});
  }
};
//获取用户资源
const getMenuTree = () => {
  let params = {
    platformTypes: [3] + "",
  };
  queryMenuTree(params).then(async (res: any) => {
    if (res && res.result) {
      if (res.result && res.result[0] && res.result[0].children) {
        // let data = JSON.parse(JSON.stringify(res.result[0].children));
        let data = res.result[0].children;
        filterMenuData(data);
        // useMainStore.updatedMenuListInfo(data); //菜单列表存储到pina中
        let data_new: any = qzsList;
        useMainStore.updatedMenuListInfo(data_new); //菜单列表存储到pina中

        let platformType = res.result[0].platformType;
        let userId = userInfo.value.id;
        // main.config.globalProperties.$mqtt = mqtt.connect(import.meta.env.VITE_MQTT_URL, getOptions())
        let mqtt_url = getMqttUrl();
        main.config.globalProperties.$mqtt = mqtt.connect(
          mqtt_url,
          getOptions()
        );
        //设置订阅主题(总平台系统公告)
        setTopics(platformType, projectId.value, userId);
        //设置订阅主题(运维平台通知公告)
        setTopics2(projectId.value, userId);
        //启动mqtt状态监听
        useMainStore.mqtt_service();
        await getenv((res_env: any) => {
          let environmentInfo = res_env.result ? res_env.result : "";
          useMainStore.updatedEnvironmentInfo(environmentInfo); //环境信息存储到pina中
        });
        //跳转第一个有pageUrl的路由
        if (res.result[0].children.length > 0) {
          // if (res.result[0].children[0].pageUrl) {
          //   router.push(res.result[0].children[0].pageUrl);
          // } else {
          //   router.push(res.result[0].children[0].children[0].pageUrl);
          // }
          router.push("/integratedServices/schedulingManage");
        } else {
          router.push("/noPermission");
        }
      } else {
        useMainStore.updatedMenuListInfo([]); //菜单列表存储到pina中
        router.push("/noPermission");
      }
    }
  });
};

//点击右侧下拉菜单
const handleCommand2 = (command: string | number | object) => {
  if (command && command == "1") {
    //打开修改密码弹窗
    dialogVisible.value = true;
  } else if (command && command == "2") {
    //打开个人信息弹窗
    dialogVisible2.value = true;
  } else if (command && command == "3") {
    //退出登录
    logout();
  }
};

//关闭修改密码弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};

//关闭个人信息弹窗
const closeDialog2 = () => {
  dialogVisible2.value = false;
};

//跳转消息页
const pushMessage = () => {
  //先判断我的消息页面是否有权限,如果没权限不跳转
  const menuListInfo = useMainStore.menuListInfo;
  let permissionBtn: any[] = [];
  menuListInfo.forEach((item: any) => {
    if (item.pageUrl == "/information/message") {
      permissionBtn = item.children ? item.children : [];
    } else {
      if (item.children && item.children.length > 0) {
        item.children.forEach((item2: any) => {
          if (item2.pageUrl == "/information/message") {
            permissionBtn = item2.children ? item2.children : [];
          }
        });
      }
    }
  });
  let hasPermission = false;
  permissionBtn.forEach((item) => {
    if (item.type === 3 && item.pageUrl && item.pageUrl.indexOf("_list") > -1) {
      hasPermission = true;
    }
  });
  if (hasPermission) {
    router.push("/information/message");
  } else {
    console.log("无权限");
    //@ts-ignore 取消单行ts验证
    ElMessageBox.alert("我的消息页面无权限", "跳转失败", {
      confirmButtonText: "确定",
      callback: (action: any) => {},
    });
  }
};
//获取消息数
const getMsgNum = () => {
  let currentProjectInfo: any = useMainStore.currentProjectInfo
    ? useMainStore.currentProjectInfo
    : {};
  if (!currentProjectInfo || !currentProjectInfo.projectId) {
    return;
  }

  userMsgCount().then((res: any) => {
    if (res.result) {
      let msgNum =
        Number(res.result.alarmMsgCount) + Number(res.result.noticeCount);
      useMainStore.updatedMsgNum(msgNum); //消息数存储到pina中
    }
  });
};

const filterRealName = (realName: string) => {
  if (realName && realName.length > 2) {
    return realName.slice(-2);
  } else {
    return realName;
  }
};

let msgInterval = ref<any>("");

onBeforeUnmount(() => {
  //页面卸载前清除定时器
  if (msgInterval.value) {
    clearInterval(msgInterval.value);
    msgInterval.value = "";
  }
});
let showDropdown = ref(false); //选择项目下拉框是否展示
let showDropdown2 = ref(false); //修改密码下拉框是否展示

//选择项目 下拉框出现/隐藏时触发
const dropdownVisibleChange = (val: boolean) => {
  showDropdown.value = val;
};
//修改密码 下拉框出现/隐藏时触发
const dropdownVisibleChange2 = (val: boolean) => {
  showDropdown2.value = val;
};
</script>

<style lang="scss" scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 72px;
  // background-color: rgba(0, 0, 0, 1);
  background-color: rgba(53, 53, 53, 1);
  // padding: 0 70px 0 16px;
  padding: 0 40px 0 16px;
}

.left_logo {
  width: 39px;
}

.left_logo2 {
  width: 142px;
}

.left,
.right {
  display: flex;
  align-items: center;

  .msg_box {
    position: relative;
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    padding: 0 20px;

    &:hover {
      background-color: rgb(112, 105, 95, 0.3);
    }

    .message {
      height: 31px;
    }

    .messageNum {
      display: inline-block;
      border-radius: 10px;
      background: rgba(230, 28, 28, 1);
      position: absolute;
      text-align: center;
      line-height: 20px;
      color: #fff;
      top: 17px;
      left: 38px;
      font-size: 12px;
      width: 20px;
      height: 20px;
      transform: none;
    }

    .messageNum2 {
      width: 22px;
      height: 22px;
      transform: scale(0.91);
    }
  }
}

.logo_text {
  font-size: 24px;
  font-weight: 500;
  letter-spacing: 0px;
  line-height: 56px;
  color: rgba(192, 164, 91, 1);
  margin-left: 12px;
  margin-top: 12px;
}

.title {
  font-size: 20px;
  font-weight: 700;
  letter-spacing: 0px;
  line-height: 56px;
  color: rgba(192, 164, 91, 1);
  margin-left: 10px;
  letter-spacing: 0.5px;
}

.title2 {
  margin-left: 14px;
  letter-spacing: 0;
}

.showDropdown2 {
  transform: rotateZ(-180deg);
}

.user {
  // margin-left: 56px;
  white-space: nowrap;
  height: 72px;
  display: flex;
  align-items: center;
  justify-content: center;
  // padding: 0 10px;
  padding: 0;

  .userName {
    display: inline-block;
    height: 72px;
    line-height: 72px;
    padding: 0 10px;
    cursor: pointer;

    &:hover {
      background-color: rgb(112, 105, 95, 0.3);
    }

    .titleRight {
      font-size: 14px;
      font-weight: 400;
      letter-spacing: 0px;
      // letter-spacing: -2px;
      color: #fff;
      text-align: center;
      white-space: nowrap;

      line-height: 32px;
      height: 32px;
      width: 32px;
      display: inline-block;
      background: rgb(143, 128, 87);
      border-radius: 50%;
    }
  }
}

// .user img {
//   margin-right: 44px;
//   cursor: pointer;
//   vertical-align: middle;
// }

.dropdown {
  margin-left: 96px;
  cursor: pointer;

  .el-dropdown {
    font-size: 14px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 56px;
    color: rgba(192, 164, 91, 1);
  }

  .img_icon {
    margin-left: 5px;
    vertical-align: middle;
  }

  .showDropdown {
    transform: rotateZ(-180deg);
  }

  .dropdown_pro {
    width: 240px;
    height: 32px;
    line-height: 30px;
    // border-radius: 3.5px;
    // border: 0.5px solid rgba(247, 221, 142, 0.3);
    border: 0.5px solid rgb(128, 128, 128);
    border-radius: 8px;
    position: relative;

    &:hover {
      background-color: rgb(112, 105, 95, 0.3);
    }

    .el-dropdown-link {
      // width: 150px;
      width: 100%;
      // text-indent: 30px;
      padding-left: 30px;

      .dropdown_text {
        width: 160px;
        display: inline-block;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        // text-align: center;
      }

      .img_icon {
        position: absolute;
        right: 30px;
        top: 15px;
      }
    }
  }
}

.el-dropdown-link:focus-visible {
  outline: none;
}
</style>
<style>
.dropdown_pro_popper {
  .el-dropdown-menu {
    padding: 13px 0;

    .el-dropdown-menu__item {
      width: 240px;
      font-size: 14px;
      position: relative;

      &:not(.is-disabled):focus {
        background-color: rgba(248, 221, 142, 0.2);
        color: rgb(48, 49, 51);
      }

      &.commonHeader_selected {
        color: rgb(192, 164, 91) !important;

        .pro_selected {
          height: 9px;
          position: absolute;
          right: 16px;
          bottom: 11px;
        }
      }

      .pro_icon {
        height: 15px;
        margin-right: 7px;
      }
    }
  }

  .el-popper__arrow {
    display: none;
  }
}

.dropdown_user_popper {
  /* inset: 60px 47px auto auto !important; */
  inset: 60px 30px auto auto !important;

  .el-dropdown-menu {
    padding-bottom: 8px;

    .el-dropdown-menu__item {
      width: 180px;
      font-size: 14px;
      position: relative;
      line-height: 45px;
      padding: 0 27px;
      color: rgb(48, 49, 51);

      &:not(.is-disabled):focus {
        background-color: rgba(0, 0, 0, 0.05);
        color: rgb(48, 49, 51);
      }

      &.dropdown_userInfo {
        flex-direction: column;
        align-items: flex-start;
        line-height: 30px;
        padding: 13px 27px;
        cursor: auto;

        &:not(.is-disabled):focus {
          background-color: #fff;
        }

        .realName {
          color: rgb(48, 49, 51);
          font-weight: 700;
        }

        .info_type {
          color: rgb(112, 105, 95);
        }
      }

      &.dropdown_change {
        padding: 0 15px;

        .change_item {
          padding-left: 12px;
          display: inline-block;
          width: 100%;
          border-top: 1px solid rgb(228, 232, 235);
          display: flex;
          align-items: center;

          .head_icon {
            width: 17px;
            margin-right: 12px;
          }
        }
      }

      &.dropdown_changePw {
        .pw {
          border-top: none;
          border-bottom: 1px solid rgb(228, 232, 235);
        }
      }

      &.dropdown_logout {
        margin-top: 8px;

        .logout {
          border-top: none;
        }
      }
    }
  }

  .el-popper__arrow {
    display: none;
  }
}
</style>
